package com.ant.backstage.config.shiro;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @ClassName:  SessionListener
 * session 自定义监听
 * @Description 统计session数量
 */
public class ShiroSessionListener implements SessionListener {

    private static Logger logger = LogManager.getLogger(ShiroSessionListener.class);

    /**
     * 统计在线人数
     * juc包下线程安全自增
     */
    private final AtomicInteger sessionCount = new AtomicInteger(0);

    /**
     * 会话创建时触发
     * @param session
     */
    @Override
    public void onStart(Session session) {
        sessionCount.incrementAndGet();
        logger.info("登录，有效session数量："+sessionCount.get());
    }

    /**
     * 退出会话时触发
     * @param session
     */
    @Override
    public void onStop(Session session) {
        sessionCount.decrementAndGet();
        logger.info("登出，有效session数量："+sessionCount.get());
    }

    /**
     * 会话过期时触发
     * @param session
     */
    @Override
    public void onExpiration(Session session) {
        sessionCount.decrementAndGet();
        logger.info("session过期，有效session数量："+sessionCount.get());
    }

    /**
     * 获取在线人数使用
     * @return
     */
    public AtomicInteger getSessionCount() {
        return sessionCount;
    }


}
